import { Component, ElementRef, ViewChild } from '@angular/core';
import { CommonModule } from '@angular/common';
import { SharedModule } from '../../../shared/shared.module';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import { DeployService } from '../deploy.service';

@Component({
  selector: 'app-project-edit-modal',
  standalone: true,
  imports: [CommonModule, SharedModule],
  template: `
      <form nz-form [formGroup]="validateForm" ngxsForm="project.modal">

          <nz-form-item>
              <nz-form-label [nzSpan]="4" nzRequired>项目名</nz-form-label>
              <nz-form-control [nzSpan]="20" [nzErrorTip]="nameErrorTpl">
                  <input nz-input formControlName="name" placeholder="请输入项目名"/>
                  <ng-template #nameErrorTpl let-control>
                      <ng-container *ngIf="control.hasError('required')">请输入项目名!</ng-container>
                  </ng-template>
              </nz-form-control>
          </nz-form-item>

          <nz-form-item>
              <nz-form-label [nzSpan]="4">标签</nz-form-label>
              <nz-form-control [nzSpan]="20">
                  <nz-tag
                          *ngFor="let tag of tags; let i = index"
                          nzMode="closeable"
                          (nzOnClose)="handleClose(tag)"
                  >
                      {{ sliceTagName(tag) }}
                  </nz-tag>
                  <nz-tag *ngIf="!inputVisible" class="editable-tag" nzNoAnimation (click)="showInput()">
                      <span nz-icon nzType="plus"></span>
                      新标签
                  </nz-tag>
                  <input
                          #inputElement
                          nz-input
                          nzSize="small"
                          *ngIf="inputVisible"
                          type="text"
                          [(ngModel)]="inputValue"
                          style="width: 78px;"
                          (blur)="handleInputConfirm()"
                          (keydown.enter)="handleInputConfirm()"
                          [ngModelOptions]="{standalone: true}"
                  />
              </nz-form-control>
          </nz-form-item>

      </form>
  `,
  styles: ``,
})
export class ProjectEditModalComponent {
  validateForm: FormGroup;
  inputValue = '';
  inputVisible = false;
  @ViewChild('inputElement', {static: false}) inputElement?: ElementRef;

  constructor(private fb: FormBuilder, private deployService: DeployService) {
    this.validateForm = this.fb.group({
      id: [''],
      name: ['', [Validators.required]],
      tags: [[]],
      createAt: [],
    });
  }

  get tags() {
    let tagsFormArray = this.validateForm.get('tags') as FormControl;
    return tagsFormArray.getRawValue();
  }

  set tags(tags: string[]) {
    let tagsFormArray = this.validateForm.get('tags') as FormControl;
    tagsFormArray.setValue([]);
    tags.forEach(s => tagsFormArray.getRawValue().push(s));
    this.validateForm.markAsDirty();
    this.validateForm.updateValueAndValidity();
  }

  handleClose(removedTag: {}): void {
    this.tags = this.tags.filter(tag => tag !== removedTag);
  }

  sliceTagName(tag: string): string {
    return this.deployService.sliceTagName(tag);
  }

  showInput() {
    this.inputVisible = true;
    setTimeout(() => {
      this.inputElement?.nativeElement.focus();
    }, 10);
  }

  handleInputConfirm() {
    if (this.inputValue && this.inputValue.trim().length > 0 && this.tags.indexOf(this.inputValue) === -1) {
      this.tags = [...this.tags, this.inputValue.trim()];
    }
    this.inputValue = '';
    this.inputVisible = false;
  }
}
